<template>
  <div>
    <el-button @click="blackPage">返回</el-button>
    <el-form
      :model="dataForm"
      ref="dataForm"
      label-width="150px"
      :disabled="isView"
    >
      <div>
        <el-steps :active="active" align-center finish-status="success">
          <el-step title="基本信息"></el-step>
          <el-step title="拓展信息"></el-step>
        </el-steps>
      </div>

      <div v-if="active == 0">
        <el-form-item label="商品平台分类">
          <!-- <span>此商品对应的类目，分类由平台管理</span> -->
          <div v-if="productClassifyMultipleSelection.length > 0">
            <el-tag
              v-for="tagIndex in productClassifyMultipleSelection"
              :key="tagIndex.name"
              closable
              :type="tagIndex.type"
              @close="productClassifyClose(tagIndex)"
            >
              {{ tagIndex.name }}
            </el-tag>
          </div>
          <el-button @click="getCategory()" v-else>选择商品类目</el-button>
        </el-form-item>
        <el-form-item label="商品店铺分组">
          <div class="flexcenter">
            <div v-if="groupingMultipleSelection.length > 0">
              <el-tag
                style="margin-right:10px"
                v-for="tagIndex in groupingMultipleSelection"
                :key="tagIndex.name"
                closable
                :type="tagIndex.type"
                @close="productGroupingClose(tagIndex)"
              >
                {{ tagIndex.name }}
              </el-tag>
            </div>
            <div class="flexcenter">
              <el-button @click="getGoodsGroupEvent()"
                >选择商品店铺分组</el-button
              >
              <span class="textWorning">请选择二级分组</span>
            </div>
          </div>
        </el-form-item>

        <!-- <el-form-item label="商品短标题">
					<el-input maxlength="10" show-word-limit v-model="dataForm.short_title" placeholder="非必填,商品短标题"></el-input>
				</el-form-item> -->
        <el-form-item label="商品名称">
          <el-input
            maxlength="50"
            v-model="dataForm.title"
            placeholder="必填,商品名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="商家编码">
          <el-input
            maxlength="20"
            v-model="dataForm.spu_code"
            placeholder="选填,与商家自由系统对接时需要"
          ></el-input>
        </el-form-item>

        <el-form-item label="商品图片">
          <Imglist
            @updataImg="updataImg"
            :limit="6"
            :value="blackImg"
          ></Imglist>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
          <!-- <span
              >尺寸建议750x750（正方形模式）或750×1000（长图模式）像素以上，大小2M以下，最多10张
              (可拖拽图片调整显示顺序 )</span
            > -->
        </el-form-item>
        <el-form-item label="商品视频">
          <videoList
            @updataVideo="updataVideo"
            :videoUrl="dataForm.video_url"
          ></videoList>
        </el-form-item>
        <el-form-item label="">
          <el-button @click="relevance">添加规格</el-button>
          <span class="textWorning">修改规格将清空填写的SKU信息</span>
        </el-form-item>

        <!-- 选择sku后 -->
        <el-form-item label="" v-if="skuList.length > 0">
          <div v-for="items in skuList" :key="items.id">
            <div>
              规格：<el-tag>{{ items.name }}</el-tag>
            </div>
            <div class="flexBox">
              <el-checkbox-group v-model="childrenListsku">
                <el-checkbox
                  v-for="sku in items.children"
                  :label="sku.name"
                  :key="sku.id"
                  :checked="sku.flag"
                  @change="handleSkusChange(sku.id)"
                  >{{ sku.name }}</el-checkbox
                >
              </el-checkbox-group>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="">
          <el-table :data="tableData" border style="width: 100%">
            <el-table-column prop="name" align="center" label="规格">
            </el-table-column>
            <el-table-column
              prop="single_goods_title"
              label="单品"
              align="center"
              width="180"
            >
            </el-table-column>
            <el-table-column
              prop="cover"
              label="图片"
              align="center"
              width="180"
            >
              <template slot-scope="scope">
                <div
                  class="imgList"
                  v-if="scope.row.cover && scope.row.cover != ''"
                >
                  <i
                    class="el-icon-remove-outline"
                    @click="delImg(scope.row.cover, scope.$index)"
                  ></i>
                  <img
                    :src="scope.row.cover"
                    style="width:80px;height:80px;"
                    alt
                  />
                </div>
                <div v-else @click="handleSingleImg(scope.row, scope.$index)">
                  <el-upload
                    action=""
                    :http-request="requestHttp"
                    :before-upload="beforeUploadHandle"
                  >
                    <el-button type="primary">选择图片</el-button>
                  </el-upload>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="bar_code"
              label="商品编码"
              align="center"
              width="140"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.bar_code"
                  maxlength="20"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="market_price"
              label="市场价格"
              align="center"
              width="140"
            >
              <template slot-scope="scope">
                <el-input-number
                  :min="0"
                  :controls="false"
                  style="width:119px"
                  :precision="2"
                  v-model="scope.row.market_price"
                  maxlength="8"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column
              prop="sale_price"
              label="销售价格"
              align="center"
              width="140"
            >
              <template slot-scope="scope">
                <el-input-number
                  :min="0"
                  :controls="false"
                  style="width:119px"
                  :precision="2"
                  v-model="scope.row.sale_price"
                  maxlength="8"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column
              prop="weight"
              label="重量(KG)"
              align="center"
              width="140"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.weight" maxlength="8"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="volume"
              label="体积(M3)"
              align="center"
              width="140"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.volume" maxlength="8"> </el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="scope">
                <el-button
                  @click="handleSingle(scope.row, scope.$index)"
                  type="text"
                  size="small"
                  >关联单品</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <!-- 批量设置 -->
        <el-form-item label="">
          <span>商品编码: </span>
          <el-input
            v-model="goodsNo"
            style="width:120px"
            maxlength="20"
          ></el-input>
          <span>市场价格: </span>
          <el-input
            v-model="goodsPrice"
            @input="limitInput($event, 'goodsPrice')"
            maxlength="8"
            style="width:120px"
          ></el-input>
          <span>销售价格: </span>
          <el-input
            v-model="retailPrice"
            @input="limitInput($event, 'retailPrice')"
            maxlength="8"
            style="width:120px"
          ></el-input>
          <span>重量: </span>
          <el-input
            v-model="weight"
            maxlength="8"
            style="width:120px"
          ></el-input>
          <span>体积: </span>
          <el-input
            v-model="volume"
            maxlength="8"
            style="width:120px"
          ></el-input>
          <el-button type="primary" @click="batchSetup">批量设置</el-button>
        </el-form-item>
        <el-form-item label="配送模板">
          <el-select
            v-model="dataForm.freight_template_id"
            placeholder="请选择运费模板"
          >
            <el-option
              v-for="item in sendModel"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </div>

      <!--拓展信息-->
      <div v-if="active == 1">
        <el-form-item label="初始销量">
          <el-input-number
            v-model="dataForm.init_sale_num"
            :min="0"
            placeholder="初始销量"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品限购">
          <el-input-number
            v-model="dataForm.limit_buy_num"
            :min="0"
            placeholder="0表示不限购"
          ></el-input-number
          ><span class="textWorning">0表示不限购</span>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number
            v-model="dataForm.sort"
            :min="0"
            placeholder="数字越大越靠前"
          ></el-input-number>
        </el-form-item>
        <!-- <el-form-item label="是否开启会员折扣">
					<el-radio-group v-model="dataForm.open_user_discount">
						<el-radio :label="false">关</el-radio>
						<el-radio :label="true">开</el-radio>
					</el-radio-group>
					<div class="el-999">
						如果不开启会员折扣，该商品则不享受会员等级折扣价
					</div>
				</el-form-item> -->
        <el-form-item label="是否热销">
          <el-radio-group v-model="dataForm.hot">
            <el-radio :label="false">否</el-radio>
            <el-radio :label="true">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否是新品">
          <el-radio-group v-model="dataForm.new_goods">
            <el-radio :label="false">否</el-radio>
            <el-radio :label="true">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否推荐">
          <el-radio-group v-model="dataForm.recommend">
            <el-radio :label="false">否</el-radio>
            <el-radio :label="true">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品详情">
          <editor @getTxt="getTxt" :value="valueDetail"></editor>
        </el-form-item>
      </div>

      <!--选择商品类目-->
      <el-dialog
        title="商品类目"
        :append-to-body="true"
        :visible.sync="dialogProductClassify"
        width="30%"
        border
      >
        <span class="textWorning">提示：点击分类即选中</span>
        <el-table
          ref="multipleTable"
          :data="productClassifyTableData"
          tooltip-effect="dark"
          style="width: 100%"
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          @row-click="rowClick"
          align="center"
        >
          <el-table-column prop="name" label="分类名称"> </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogProductClassify = false">取 消</el-button>
        </span>
      </el-dialog>

      <!--选择商品分组-->
      <el-dialog
        title="商品分组"
        :append-to-body="true"
        :visible.sync="dialogProductGrouping"
        width="30%"
      >
        <el-table
          ref="multipleTables"
          :data="productGroupingTableData"
          tooltip-effect="dark"
          border
          style="width: 100%"
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          @selection-change="productGroupingSelectionChange"
        >
          <el-table-column
            type="selection"
            :selectable="selectable"
            width="55"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="name" label="分类名称" align="center">
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogProductGrouping = false">取 消</el-button>
          <el-button type="primary" @click="dialogProduct">确 定</el-button>
        </span>
      </el-dialog>
      <!--选择规格-->
      <el-dialog
        title="添加规格"
        :append-to-body="true"
        :visible.sync="dialogSku"
        width="30%"
      >
        <el-table
          ref="multipleTable"
          :data="skuData"
          tooltip-effect="dark"
          style="width: 100%"
          border
          @selection-change="productSku"
        >
          <el-table-column type="selection" width="80" align="center">
          </el-table-column>
          <el-table-column prop="name" label="规格名称" align="center">
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogSku = false">取 消</el-button>
          <el-button type="primary" @click="dialogSkuChoose">确 定</el-button>
        </span>
      </el-dialog>
    </el-form>
    <!-- <el-button @click="visible = false">提交</el-button> -->
    <el-button class="btn" v-if="active == 0" type="primary" @click="next"
      >下一步</el-button
    >
    <el-button class="btn" v-if="active == 1" @click="updown">上一步</el-button>
    <el-button
      :disabled="isView"
      v-if="active == 1"
      type="primary"
      @click="submitInfo"
      >提交</el-button
    >
    <singleGoods
      v-if="singleShow"
      ref="itemAddUpdate"
      @singleShowOnchange="singleShowOnchange"
    ></singleGoods>
  </div>
</template>

<script>
import serviceApione from '@/api/serviceApione.js'
import { treeDataTranslate } from '@/utils'
import Imglist from './../../oss/oss-uploadImg'
import videoList from './../../oss/oss-uploadvideo'
import editor from '@/components/editor'
import singleGoods from './singleGoods'
import axios from 'axios'
import Vue from 'vue'
export default {
  components: {
    Imglist,
    videoList,
    editor,
    singleGoods
  },
  data() {
    return {
      isView: false,
      editorId: '',
      blackImg: [], // 编辑商品图片
      goodsNo: '',
      goodsPrice: '',
      retailPrice: '',
      updataArr: [],
      valueDetail: '',
      weight: '',
      volume: '',
      retailPrice: null,
      goodsPrice: null,
      weight: null,
      volume: null,
      visible: false,
      singleShow: false,
      active: 0, // 步骤初始化
      is_member: 0, // 是否开启会员折扣
      dataForm: {
        id: null,
        category_id: null,
        goods_group_ids: [],
        short_title: '',
        title: '',
        spu_code: '',
        images: [],
        freight_template_id: null,
        init_sale_num: null,
        limit_buy_num: null,
        sort: null,
        open_user_discount: false,
        hot: false,
        new_goods: false,
        recommend: false,
        mobile_detail: '',
        sku_table: [],
        goods_sku_list: []
      },
      dataRule: [], // 提交提示
      skuAllId: [], // 选中的skuid集合
      dialogImageUrl: '',
      dialogVisible: false,
      dialogProductClassify: false, // 商品分类弹窗
      dialogProductGrouping: false,
      productClassifyMultipleSelection: [],
      productClassifyTableData: [],
      productGroupingTableData: [], // 商品分组table数据
      groupingMultipleSelection: [], // 提交循环商品分组
      groupSelection: [], // 选中的商品分组
      radioSpec: '1', // 商品规格
      tableData: [
        {
          single_goods_title: '',
          cover: '',
          bar_code: '',
          market_price: null,
          sale_price: null,
          weight: null,
          volume: null
        }
      ], // 单规格
      uploadVisible: false,
      choseSkuTable: [], // 编辑回显的sku
      skuData: [], // 规格table
      dialogSku: false,
      ids: [], // 选中规格
      skuList: [],
      childrenListsku: [],
      changeArr: [], // 选中的数据
      sendModel: [], // 运费模板
      choseIndex: '', // 选中的列表下标
      skuLocEditor: false
    }
  },
  mounted() {
    this.freighttemplateData()
    let id = this.$route.query.id
    let type = this.$route.query.type
    if (type == 'view') {
      this.isView = true
    } else {
      this.isView = false
    }
    if (id) {
      this.skuLocEditor = true
      this.editorId = id
      this.dataForm.id = id
      this.goodsInfoData(id)
    }
  },
  methods: {
    limitInput(value, name) {
      this[name] =
        ('' + value) // 第一步：转成字符串
          .replace(/[^\d^\.]+/g, '') // 第二步：把不是数字，不是小数点的过滤掉
          .replace(/^0+(\d)/, '$1') // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
          .replace(/^\./, '0.') // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
          .match(/^\d*(\.?\d{0,2})/g)[0] || '' // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到2位小数
    },
    // 编辑
    goodsInfoData(id) {
      serviceApione.goodsInfo(id).then(res => {
        if (res.data.code == 200) {
          let target = res.data.data
          let eids = [],
            goodsIds = []
          this.getCategoryList(target.category_id)
          this.dataForm.category_id = target.category_id
          this.dataForm.short_title = target.short_title
          this.dataForm.title = target.title
          this.dataForm.spu_code = target.spu_code
          this.groupingMultipleSelection = target.group_list
          target.group_list.forEach(item => {
            goodsIds.push(item.id)
          })
          this.dataForm.images = target.images
          this.dataForm.goods_group_ids = goodsIds
          this.blackImg = target.images
          this.dataForm.video_url = target.video_url
          this.choseSkuTable = target.sku_table
          target.goods_sku_list.forEach(key => {
            key.name = key.sku_set_name
            this.skuAllId.push({
              id: key.sku_hash_code
            })
          })
          this.tableData = target.goods_sku_list
          this.dataForm.freight_template_id = target.freight_template_id
          // sku回显
          target.sku_table.forEach(item => {
            eids.push(item.head.id)
          })

          this.dataForm.init_sale_num = target.init_sale_num
          this.dataForm.limit_buy_num = target.limit_buy_num
          this.dataForm.sort = target.sort
          this.dataForm.open_user_discount = target.open_user_discount
          this.dataForm.hot = target.hot
          this.dataForm.new_goods = target.new_goods
          this.dataForm.recommend = target.recommend
          this.dataForm.mobile_detail = target.mobile_detail
          this.valueDetail = target.mobile_detail
          this.skuListGet(eids)
        }
      })
    },
    // 编辑回选分类
    blackText(id) {},
    selectable(row, index) {
      if (row.parent_id > 0) {
        return true
      } else {
        return false
      }
    },
    // 上传之前
    beforeUploadHandle(file) {
      console.log(file)
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG /png格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return (isJPG || isPNG) && isLt2M
    },
    // 随机生成文件名
    random_string(len) {
      len = len || 32
      var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789'
      var maxPos = chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    requestHttp(file) {
      let formData = new FormData()
      formData.append('file', file.file)
      let config = {
        headers: {
          token: Vue.cookie.get('token'),
          'Content-Type': 'multipart/form-data'
        }
      }
      this.uploadLoding = true
      axios
        .post(
          `${this.$config.SERVER_URL}/admin/sys/oss/upload`,
          formData,
          config
        )
        .then(obj => {
          if (obj.status == 200) {
            let fileUrl = obj.data.data.url
            this.updataArr.push(fileUrl)
            this.tableData[this.choseIndex].cover = fileUrl
          }
        })
    },
    // 删除图片
    delImg(row, index) {
      this.tableData[index].cover = ''
    },
    // 上传图片
    handleSingleImg(row, index) {
      this.choseIndex = index
    },
    // 关联单品
    handleSingle(row, index) {
      this.singleShow = true
      this.choseIndex = index
      console.log(row, index)
      this.$nextTick(() => {
        this.$refs.itemAddUpdate.init()
      })
    },
    singleShowOnchange(val) {
      debugger
      if (val) {
        this.$nextTick(() => {
          this.tableData[this.choseIndex].single_goods_title = val.title
          this.tableData[this.choseIndex].singleData = val
        })
        console.log(this.tableData)
        this.singleShow = false
      }
    },
    // 编辑器
    getTxt(e) {
      this.dataForm.mobile_detail = e
    },
    // 上传视频
    updataVideo(e) {
      console.log(e)
      this.dataForm.video_url = e
    },
    // 上传图片
    updataImg(e) {
      debugger
      this.dataForm.images = e
    },
    // 批量设置
    batchSetup() {
      if (this.tableData.length <= 0) {
        layer.alert('至少需要一条商品Sku')
        return
      }
      this.tableData.forEach(val => {
        val.bar_code = this.goodsNo
        val.market_price = this.goodsPrice
        val.weight = this.weight
        val.volume = this.volume
        val.sale_price = this.retailPrice
      })
      this.$forceUpdate()
    },
    handleSkusChange(id) {
      // 存name
      let skuArr = []
      let skuOne = []
      let skuTwo = []
      let skuThree = []
      // 存id
      let skuArrid = []
      let skuOneid = []
      let skuTwoid = []
      let skuThreeid = []
      this.skuList.forEach(item => {
        item.children.forEach(keys => {
          if (keys.id == id) {
            keys.flag = !keys.flag
          }
        })
      })
      if (this.skuList.length == 1) {
        this.skuList[0].children.forEach(keys => {
          if (keys.flag) {
            skuOne.push(keys.name)
            skuOneid.push(keys.id)
          }
        })
        this.tableData = []
        this.skuAllId = []
        if (skuOne.length > 0) {
          skuOne.forEach(name => {
            this.tableData.push({
              name: name,
              single_goods_title: '',
              bar_code: '',
              cover: ''
            })
          })
          skuOneid.forEach(id => {
            this.skuAllId.push({
              id: id
            })
          })
        } else {
          this.skuAllId = []
          this.tableData = [
            {
              single_goods_title: '',
              cover: '',
              bar_code: '',
              market_price: null,
              sale_price: null,
              weight: null,
              volume: null
            }
          ]
        }
      }
      if (this.skuList.length == 2) {
        this.skuList[0].children.forEach(keys => {
          if (keys.flag) {
            skuOne.push(keys.name)
            skuOneid.push(keys.id)
          }
        })
        this.skuList[1].children.forEach(keys => {
          if (keys.flag) {
            skuTwo.push(keys.name)
            skuTwoid.push(keys.id)
          }
        })
        skuArr.push(skuOne, skuTwo)
        skuArrid.push(skuOneid, skuTwoid)
        console.log(skuArrid)
      }
      if (this.skuList.length == 3) {
        this.skuList[0].children.forEach(keys => {
          if (keys.flag) {
            skuOne.push(keys.name)
            skuOneid.push(keys.id)
          }
        })
        this.skuList[1].children.forEach(keys => {
          if (keys.flag) {
            skuTwo.push(keys.name)
            skuTwoid.push(keys.id)
          }
        })
        this.skuList[2].children.forEach(keys => {
          if (keys.flag) {
            skuThree.push(keys.name)
            skuThreeid.push(keys.id)
          }
        })

        skuArr.push(skuOne, skuTwo, skuThree)
        skuArrid.push(skuOneid, skuTwoid, skuThreeid)
      }

      if (this.skuList.length > 1) {
        // console.log(this.descartes(skuArr))
        this.tableData = []
        this.skuAllId = []
        let arrBox = this.descartes(skuArr)
        let arrBoxid = this.descartes(skuArrid)
        if (arrBox.length > 0) {
          arrBox.forEach(name => {
            this.tableData.push({
              name: name.join(';'),
              single_goods_title: '',
              bar_code: '',
              cover: ''
            })
          })
          arrBoxid.forEach(id => {
            this.skuAllId.push({
              id: id.join('|')
            })
          })
        } else {
          this.skuAllId = []
          this.tableData = [
            {
              single_goods_title: '',
              cover: '',
              bar_code: '',
              market_price: null,
              sale_price: null,
              weight: null,
              volume: null
            }
          ]
        }
      }
    },
    // 选择sku后请求
    dialogSkuChoose() {
      this.skuLocEditor = false
      this.skuAllId = []
      this.tableData = [
        {
          single_goods_title: '',
          cover: '',
          bar_code: '',
          market_price: null,
          sale_price: null,
          weight: null,
          volume: null
        }
      ]
      if (this.ids.length < 4 && this.ids.length > 0) {
        this.skuListGet(this.ids)
      } else {
        this.$message.warning('请选择1-3条规格~')
      }
    },

    // 选中sku获取列表
    skuListGet(id) {
      serviceApione.selectSku(id).then(res => {
        if (res.data.code == 200) {
          this.childrenListsku = []
          this.skuList = res.data.list
          this.skuList.forEach(item => {
            item.children.forEach(keys => {
              keys.flag = false
            })
          })
          if (this.editorId && this.skuLocEditor) {
            this.skuList.forEach(item => {
              item.children.forEach(keys => {
                this.choseSkuTable.forEach(l => {
                  l.values.forEach(j => {
                    if (keys.id == j.id) {
                      keys.flag = true
                    }
                  })
                })
              })
            })
          }
          this.dialogSku = false
        }
      })
    },
    // 选择规格
    productSku(e) {
      let ids = []
      e.forEach(item => {
        ids.push(item.id)
      })
      this.ids = ids
    },
    // 运费模板数据
    freighttemplateData() {
      serviceApione.freighttemplate().then(res => {
        if (res.data.code == 200) {
          this.sendModel = res.data.list
          if (res.data.list.length > 0) {
            this.dataForm.freight_template_id = res.data.list[0].id
          }
        }
      })
    },
    // 添加规格
    relevance() {
      this.dialogSku = true
      serviceApione.getSkuTop().then(res => {
        if (res.data.code == 200) {
          this.skuData = res.data.list
        }
      })
    },
    // 笛卡尔
    descartes(array) {
      // [ ['黑色', '白色', '蓝色'], ['1.2KG', '2.0KG', '3.0KG'] ]
      let that = this
      that.tableData = []
      if (array.length < 2) return array[0] || []
      return [].reduce.call(array, function(col, set) {
        var res = []
        col.forEach(function(c) {
          set.forEach(function(s) {
            var t = [].concat(Array.isArray(c) ? c : [c])
            t.push(s)
            res.push(t)
          })
        })
        return res
      })
    },

    // 选中图片
    selectImgList(images) {
      this.skuTableData[this.selectIndex].cover = images[0].fileUrl
    },
    blackPage() {
      if (this.isView) {
        this.$router.go(-1)
      } else {
        this.$router.push({
          path: 'merchant-product/productList',
          query: {
            id: this.editorId
          }
        })
      }
    },
    // 查询所有商品分类
    getCategory() {
      this.dialogProductClassify = true
      this.getCategoryList('')
    },
    // 查询所有商品分类
    getCategoryList(id) {
      serviceApione.getCategory().then(res => {
        if (res.data.code == 200) {
          this.productClassifyTableData = res.data.list
          if (this.editorId) {
            res.data.list.forEach(k => {
              if (k.id == id) {
                this.productClassifyMultipleSelection = [k]
              } else {
                k.children.forEach(j => {
                  if (j.id == id) {
                    this.productClassifyMultipleSelection = [j]
                  }
                })
              }
            })
          }
        }
      })
    },
    // 商品分类选中
    rowClick(e) {
      this.dialogProductClassify = false
      this.dataForm.category_id = e.id
      this.productClassifyMultipleSelection = [e]
    },
    // 移除选中的商品分类
    productClassifyClose(tagIndex) {
      this.productClassifyMultipleSelection.splice(
        this.productClassifyMultipleSelection.indexOf(tagIndex),
        1
      )
      this.dataForm.category_id = null
    },
    // 查询所有商品分组
    getGoodsGroupEvent() {
      this.dialogProductGrouping = true
      this.getGoodsGroupList()
    },
    // 查询所有商品分组
    getGoodsGroupList() {
      serviceApione.getGoodsGroup().then(res => {
        if (res.data.code == 200) {
          this.productGroupingTableData = res.data.list
          if (this.groupingMultipleSelection.length > 0) {
            this.groupingMultipleSelection.forEach(key => {
              res.data.list.forEach(e => {
                e.children.forEach(k => {
                  if (k.id == key.id) {
                    this.$nextTick(() => {
                      this.$refs.multipleTables.toggleRowSelection(k)
                    })
                  }
                })
              })
            })
          }
        }
      })
    },
    // 移除选中的商品分组
    productGroupingClose(tagIndex) {
      this.groupingMultipleSelection.splice(
        this.groupingMultipleSelection.indexOf(tagIndex),
        1
      )
    },
    // 上一步
    updown() {
      this.active = 0
    },
    // 步骤
    next() {
      if (!this.dataForm.category_id) {
        this.$message.warning('请选择商品类目')
      } else if (this.dataForm.goods_group_ids.length == 0) {
        this.$message.warning('请选店铺分组')
      } else if (!this.dataForm.title) {
        this.$message.warning('请输入商品标题')
      } else if (this.dataForm.images.length == 0) {
        this.$message.warning('请上传图片')
      } else {
        let flag = true,
          flag1 = true,
          flag2 = true,
          flag3 = true,
          flag4 = true,
          flag5 = true,
          flag6 = true
        this.tableData.forEach(item => {
          if (item.single_goods_title) {
          } else {
            flag = false
          }

          if (item.cover) {
          } else {
            flag1 = false
          }
          if (item.bar_code) {
          } else {
            flag2 = false
          }
          if (item.market_price > 0) {
          } else {
            flag3 = false
          }
          if (item.sale_price > 0) {
          } else {
            flag4 = false
          }
          if (item.weight >= 0) {
          } else {
            flag5 = false
          }
          if (item.volume >= 0) {
          } else {
            flag6 = false
          }
        })
        if (!flag) {
          this.$message.warning('请关联单品')
          return false
        }
        if (!flag1) {
          this.$message.warning('请上传sku图片')
          return false
        }
        if (!flag2) {
          this.$message.warning('请输入商品编码')
          return false
        }
        if (!flag3) {
          this.$message.warning('请输入市场价格')
          return false
        }
        if (!flag4) {
          this.$message.warning('请输入销售价格')
          return false
        }
        if (!flag5) {
          this.$message.warning('请输入重量')
          return false
        }
        if (!flag6) {
          this.$message.warning('请输入体积')
          return false
        }
        if (!this.dataForm.freight_template_id) {
          this.$message.warning('请选择运费模板')
          return false
        }
        this.active = 1
      }
      console.log(this.tableData)
    },
    // 提交接口
    submitInfo() {
      // 组装json数据
      if (this.skuList.length == 0) {
        // 没有规格
        let idEid = this.skuLocEditor
        let singleData = this.tableData[0].singleData
        let tableData = this.tableData[0]
        this.dataForm.sku_table = []
        this.dataForm.goods_sku_list = [
          {
            single_goods_id: idEid ? tableData.single_goods_id : singleData.id,
            single_goods_title: idEid
              ? tableData.single_goods_title
              : singleData.title,
            single_goods_code: idEid
              ? tableData.single_goods_code
              : singleData.code,
            bar_code: tableData.bar_code,
            market_price: tableData.market_price,
            sale_price: tableData.sale_price,
            weight: tableData.weight,
            volume: tableData.volume,
            cover: tableData.cover,
            sku_sets: [],
            exchange_point: 0
          }
        ]
      } else if (this.skuList.length == 1) {
        // 一规格
        let hearVal = []
        let head = {}
        let idEid = this.skuLocEditor
        this.skuList.forEach(keys => {
          keys.children.forEach(val => {
            if (val.flag) {
              hearVal.push({
                name: val.name,
                id: val.id
              })
            }
          })
          head = {
            name: keys.name,
            id: keys.id
          }
        })
        this.dataForm.sku_table = [
          {
            head: head,
            values: hearVal
          }
        ]

        // 处理组装goods_sku_list
        let goodsSkuList = []
        let skuSet = []
        console.log(this.skuAllId)
        this.tableData.map((v, i) => {
          skuSet.push({
            value: {
              name: v.name,
              id: this.skuAllId[i].id
            }
          })
          goodsSkuList.push({
            single_goods_id: idEid ? v.single_goods_id : v.singleData.id,
            single_goods_title: idEid
              ? v.single_goods_title
              : v.singleData.title,
            single_goods_code: idEid ? v.single_goods_code : v.singleData.code,
            bar_code: v.bar_code,
            market_price: v.market_price,
            sale_price: v.sale_price,
            weight: v.weight,
            volume: v.volume,
            cover: v.cover,
            sku_sets: [skuSet[i]],
            exchange_point: 0
          })
        })
        this.dataForm.goods_sku_list = goodsSkuList
      } else {
        // 多规格
        // 组装
        let idEid = this.skuLocEditor
        let checkArr = this.skuList
        let hearVal1 = [],
          hearVal2 = [],
          hearVal3 = [],
          hearVals = [],
          head = []

        if (checkArr.length == 2) {
          checkArr[0].children.forEach(v1 => {
            if (v1.flag) {
              hearVal1.push({
                name: v1.name,
                id: v1.id
              })
            }
          })
          checkArr[1].children.forEach(v2 => {
            if (v2.flag) {
              hearVal2.push({
                name: v2.name,
                id: v2.id
              })
            }
          })
          hearVals.push(hearVal1, hearVal2)
        } else {
          checkArr[0].children.forEach(v1 => {
            if (v1.flag) {
              hearVal1.push({
                name: v1.name,
                id: v1.id
              })
            }
          })
          checkArr[1].children.forEach(v2 => {
            if (v2.flag) {
              hearVal2.push({
                name: v2.name,
                id: v2.id
              })
            }
          })
          checkArr[2].children.forEach(v3 => {
            if (v3.flag) {
              hearVal3.push({
                name: v3.name,
                id: v3.id
              })
            }
          })
          hearVals.push(hearVal1, hearVal2, hearVal3)
        }
        checkArr.map((v, i) => {
          head.push({
            name: v.name,
            id: v.id
          })
          this.dataForm.sku_table.push({
            head: head[i],
            values: hearVals[i]
          })
        })
        // 处理组装goods_sku_list
        let skuSet = []
        let goodsSkuList = []
        this.skuAllId.map((v, i) => {
          let skuId = v.id.split('|')
          let smallSku = []
          skuId.forEach(vs => {
            this.skuList.forEach(keys => {
              keys.children.forEach(val => {
                if (vs == val.id) {
                  smallSku.push({
                    value: {
                      name: val.name,
                      id: val.id
                    }
                  })
                }
              })
            })
          })
          skuSet.push(smallSku)
        })
        this.tableData.map((v, i) => {
          goodsSkuList.push({
            single_goods_id: idEid ? v.single_goods_id : v.singleData.id,
            single_goods_title: idEid
              ? v.single_goods_title
              : v.singleData.title,
            single_goods_code: idEid ? v.single_goods_code : v.singleData.code,
            bar_code: v.bar_code,
            market_price: v.market_price,
            sale_price: v.sale_price,
            weight: v.weight,
            volume: v.volume,
            cover: v.cover,
            sku_sets: skuSet[i],
            exchange_point: 0
          })
        })
        this.dataForm.goods_sku_list = goodsSkuList
      }
      console.log(this.dataForm)
      if (this.editorId) {
        serviceApione.goodsUpdate(this.dataForm).then(res => {
          if (res && res.data.code == 200) {
            this.$message.success('编辑成功')
            this.$router.push({
              path: 'merchant-product/productList',
              query: {
                id: this.editorId
              }
            })
          }
        })
      } else {
        serviceApione.goodsCreate(this.dataForm).then(res => {
          if (res && res.data.code == 200) {
            this.$message.success('发布成功')
            this.$router.push({
              path: 'merchant-product/productList',
              query: {
                id: this.editorId
              }
            })
          }
        })
      }
    },

    // 商品分组
    // 选中
    productGroupingSelectionChange(val) {
      this.groupSelection = val
    },
    // 确定提交数据
    dialogProduct() {
      let goodsIds = []
      this.groupingMultipleSelection = this.groupSelection
      this.groupSelection.forEach(item => {
        goodsIds.push(item.id)
      })
      this.dialogProductGrouping = false
      this.dataForm.goods_group_ids = goodsIds
    }
  }
}
</script>

<style lang="scss">
.textWorning {
  font-size: 13px;
  color: #999;
  padding-left: 8px;
}
.flexBox {
  display: flex;
  align-items: center;
}
.flexcenter {
  display: flex;
  align-items: center;
}
.upbtns {
  position: relative;
  width: 100%;
  height: 36px;

  .upimgBtn {
    opacity: 0;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 36px;
    z-index: 3;

    input {
      width: 100%;
      height: 36px;
      display: block;
    }
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
}

.el-999 {
  color: #999999;
}

.btn {
  margin-left: 50px;
}
</style>
